/**     
 * @Title: SecurityConfig.java   
 * @Package me.springboot.security   
 * @Description: TODO
 * @author weiwei 
 * @date 2017年9月1日 上午10:14:15   
 * @version V1.0     
 */
package me.springboot.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @ClassName: SecurityConfig
 * @Description: 安全配置文件，主要是重写默认的认证方式和访问目录权限
 * @author weiwei
 * @date 2017年9月1日 上午10:14:15
 * 
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Bean
	public UserDetailsService customUserService() {
		return new CustomUserService();
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder builder) throws Exception {
		builder.userDetailsService(customUserService()).passwordEncoder(new BCryptPasswordEncoder(10));
	}

	@Configuration
	@Order(1)
	public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
		protected void configure(HttpSecurity http) throws Exception {
			http.antMatcher("/api/i/**").authorizeRequests().anyRequest().hasRole("USER").and().httpBasic();
		}
	}

	@Configuration
	@Order(2)
	public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
		@Override
		protected void configure(HttpSecurity http) throws Exception {
			http.authorizeRequests().antMatchers("/api/create", "/", "/assets/**", "/plugins/**", "/bootstrap/**", "/api-docs/**", "/debug/**", "/api/**", "/lightadmin").permitAll()
					.antMatchers("/admin/**").hasRole("ADMIN").anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout().permitAll().and()
					.csrf().disable();
		}
	}
}